import Vue from 'vue';
import Router from 'vue-router';
import Login from '@/views/Login';
import NotFound from '@/views/Error/404';
import Home from '@/views/Home';
import FirstPage from '@/views/FirstPage';
import perCenter from '@/views/Intro/PerCenter';
import Generator from '@/views/Generator/Generator';
import api from '@/http/api';
import store from '@/store';
import md5 from 'js-md5';
import Rsa from '@/utils/rsa.js';

import { getIFramePath, getIFrameUrl } from '@/utils/iframe';

// 导入设备列表评论接口
import { senseLinkLogin } from '@/api/comment/EquipmentList';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      name: '首页',
      component: Home,
      children: [
        {
          path: '/',
          name: '数据总览',
          component: FirstPage
        },
        {
          path: '/perCenter',
          name: '个人中心',
          component: perCenter,
          meta: {
            icon: 'fa fa-home fa-lg',
            index: 1
          }
        }
      ]
    },
    {
      path: '/login',
      name: '登录',
      component: Login
    },
    {
      path: '/404',
      name: 'notFound',
      component: NotFound
    }
  ]
});

router.beforeEach((to, from, next) => {
  // 登录界面登录成功之后，会把用户信息保存在会话
  // 存在时间为会话生命周期，页面关闭即失效。
  let token = sessionStorage.getItem('token');
  let userName = sessionStorage.getItem('userinfo');
  
  console.log('当前路由:', to.path);
  console.log('当前token状态:', token ? '已登录' : '未登录');
  
  // 检查是否存在Authorization参数 - 从URL的search和hash部分都尝试获取
  let authToken = getQueryString('Authorization') || getHashQueryString('Authorization');
  
  console.log('从URL获取到的Authorization参数:', authToken);
  
  if (authToken && !token) {
    console.log('检测到Authorization参数且未登录，开始处理自动登录');
    // 如果有Authorization参数但还没有登录token，调用新接口获取账号密码
    handleAuthorizationLogin(authToken).then(() => {
      console.log('自动登录成功，跳转到首页');
      next({ path: '/' });
    }).catch((error) => {
      console.error('自动登录失败，跳转到登录页:', error);
      next({ path: '/login' });
    });
  } else if (authToken && token) {
    console.log('检测到Authorization参数但已登录，忽略自动登录');
  } else if (!authToken && !token) {
    console.log('未检测到Authorization参数且未登录');
  }

  // 获取传递的参数
  let search = window.location.hash.split('#/')[1];
  let params = {
    username: GetIframeQueryString(search, 'username'),
    password: GetIframeQueryString(search, 'password')
  };
  if (params.username && params.password && to.path === '/') {
    login(params).then((res) => {
      next({ path: '/' });
    });
  } else if (to.path === '/login') {
    // 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
    if (token) {
      next({ path: '/' });
    } else {
      next();
    }
  } else {
    if (!token) {
      // 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
      next({ path: '/login' });
    } else {
      // 加载动态菜单和路由
      addDynamicMenuAndRoutes(userName, to, from);
      next();
    }
  }
});

// 从URL中获取参数
function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return decodeURIComponent(r[2]);
  }
  return null;
}

// 从URL的hash部分获取参数
function getHashQueryString(name) {
  var hash = window.location.hash;
  var index = hash.indexOf('?');
  if (index > -1) {
    var hashSearch = hash.substring(index + 1);
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = hashSearch.match(reg);
    if (r != null) {
      return decodeURIComponent(r[2]);
    }
  }
  return null;
}

// 处理Authorization登录
function handleAuthorizationLogin(authToken) {
  return new Promise((resolve, reject) => {
    console.log('开始处理Authorization登录，token:', authToken)
    
    // 使用senseLinkLogin接口获取登录信息
    senseLinkLogin({ token: authToken })
      .then(res => {
        console.log('senseLinkLogin接口返回数据:', res)
        
        if (res.code === 0 && res.data && res.data.username && res.data.password) {
          console.log('成功获取到账号密码，准备调用登录方法')
          // 获取到账号密码后调用登录方法
          login({
            username: res.data.username,
            password: res.data.password
          }).then(() => {
            console.log('登录成功')
            resolve()
          }).catch(err => {
            console.error('登录失败:', err)
            reject(err)
          })
        } else {
          console.error('获取登录信息失败，返回数据不符合预期', res)
          reject(new Error('获取登录信息失败: ' + JSON.stringify(res)))
        }
      })
      .catch(err => {
        console.error('调用获取登录信息接口失败:', err)
        reject(err)
      })
  })
}

const login = (params) => {
  return new Promise((resolve, rej) => {
    // let password = md5(params.password);
    let password = params.password;
    let rsa = new Rsa();
    let aesrsa = rsa.RSAencrypt(rsa.key + rsa.iv);
    api.user.get_server_timestamp().then((rs) => {
      let timestamp = rs.code === 0 && rs.data ? rs.data : new Date().getTime();
      let userInfo = {
        username: rsa.encrypt(params.username),
        password: rsa.encrypt(password),
        aesrsa: aesrsa,
        timestamp: timestamp,
        sign: md5(`${params.username}#${password}#${rsa.key + rsa.iv}#${timestamp}`)
      };
      api.login
        .login(userInfo)
        .then((res) => {
          if (res.code == 0) {
            sessionStorage.setItem('lastTime', new Date().getTime());
            sessionStorage.setItem('token', res.data.token);
            sessionStorage.setItem('userInfo', JSON.stringify(res.data.user));
            // Vue.$store.commit('menuRouteLoaded', false); // 要求重新加载导航菜单
            sessionStorage.setItem('group', JSON.stringify(res.data.group)); // 保存用户到本地会话
            sessionStorage.setItem('userID', JSON.stringify(res.data.user)); // 保存用户到本地会话
            sessionStorage.setItem('account', params.username); // 保存账号
            sessionStorage.setItem('password', params.password); // 保存密码
            sessionStorage.setItem('keyiv', JSON.stringify({ key: rsa.key, iv: rsa.iv })); // AES key iv
            sessionStorage.setItem('timestamp', new Date().getTime()); // 本地获取token时间戳
            // loginForm
            // Vue.$store.commit('setAccount', params);
            // Vue.initDict();
            resolve();
          } else {
            rej(new Error(res.msg || '登录失败'));
          }
        })
        .catch((res) => {
          console.log(res);
          rej(res);
        });
    });
  });
};

let GetIframeQueryString = (search, name) => {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = search.substr(1).match(reg);
  if (r != null) {
    return decodeURI(r[2]);
  }
  return null;
};

/**
 * 加载动态菜单和路由
 */
function addDynamicMenuAndRoutes(userName, to, from) {
  // 处理IFrame嵌套页面
  handleIFrameUrl(to.path);
  if (store.state.app.menuRouteLoaded) {
    return;
  }
  var token = sessionStorage.getItem('token');

  let params = {
    where: {
      'info.type': { $in: [0, 1] }
    }
  };
  let aaa = JSON.stringify(params);
  api.menu
    .findMenuTree()
    .then((res) => {
      // 添加动态路由
      let dynamicRoutes = addDynamicRoutes(res.data);
      // 处理静态组件绑定路由
      handleStaticComponent(router, dynamicRoutes);
      router.addRoutes(router.options.routes);
      // 保存加载状态
      store.commit('menuRouteLoaded', true);
      // 保存菜单树
      store.commit('setNavTree', res.data);
    })
    .then((res) => {
      api.user.findPermissions({ name: userName }).then((res) => {
        // 保存用户权限标识集合
        store.commit('setPerms', res);
      });
    })
    .catch(function (res) {});
}

/**
 * 处理路由到本地直接指定页面组件的情况
 * 比如'代码生成'是要求直接绑定到'Generator'页面组件
 */
function handleStaticComponent(router, dynamicRoutes) {
  for (let j = 0; j < dynamicRoutes.length; j++) {
    if (dynamicRoutes[j].name == '代码生成') {
      dynamicRoutes[j].component = Generator;
      break;
    }
  }
  router.options.routes[0].children = router.options.routes[0].children.concat(dynamicRoutes);
}

/**
 * 处理IFrame嵌套页面
 */
function handleIFrameUrl(path) {
  // 嵌套页面，保存iframeUrl到store，供IFrame组件读取展示
  let url = path;
  let length = store.state.iframe.iframeUrls.length;
  for (let i = 0; i < length; i++) {
    let iframe = store.state.iframe.iframeUrls[i];
    if (path != null && path.endsWith(iframe.path)) {
      url = iframe.url;
      store.commit('setIFrameUrl', url);
      break;
    }
  }
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicRoutes(menuList = [], routes = []) {
  var temp = [];
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children);
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '');
      // 创建路由配置
      var route = {
        path: menuList[i].url,
        component: null,
        name: menuList[i].name,
        meta: {
          icon: menuList[i].icon,
          index: menuList[i].id
        }
      };
      let path = getIFramePath(menuList[i].url);
      if (path) {
        // 如果是嵌套页面, 通过iframe展示
        route['path'] = path;
        route['component'] = (resolve) => require([`@/views/IFrame/IFrame`], resolve);
        // 存储嵌套页面路由路径和访问URL
        let url = getIFrameUrl(menuList[i].url);
        let iFrameUrl = { path: path, url: url };
        store.commit('addIFrameUrl', iFrameUrl);
      } else {
        try {
          // 根据菜单URL动态加载vue组件，这里要求vue组件须按照url路径存储
          // 如url="sys/user"，则组件路径应是"@/views/sys/user.vue",否则组件加载不到
          let array = menuList[i].url.split('/');
          // let url = '';
          // for (let i = 0; i < array.length; i++) {
          //   url += array[i].substring(0, 1).toUpperCase() + array[i].substring(1) + '/';
          // }
          // url = url.substring(0, url.length - 1);
          let url = array
            .map(
              (part, index) =>
                index === array.length - 1 && part.toLowerCase() === 'index'
                  ? 'index' // 最后一级是 index，保持小写
                  : part.charAt(0).toUpperCase() + part.slice(1) // 否则转 PascalCase
            )
            .join('/');
          console.log(url);
          route['component'] = (resolve) => require([`@/views/${url}`], resolve);
        } catch (e) {}
      }
      routes.push(route);
    }
  }
  if (temp.length >= 1) {
    addDynamicRoutes(temp, routes);
  } else {
    console.log('动态路由加载...');
    //  console.log(routes)
    //  console.log('动态路由加载完成.')
  }
  return routes;
}

export default router;
